package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R save(@RequestBody Category category) {
        log.info("新增分类，category={}", category);
        categoryService.save(category);
        return R.success();
    }

    @GetMapping("/page")
    public R<Page<Category>> page(@RequestParam(required = false, defaultValue = "1") Integer page,
                                  @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        log.info("执行页面查询...page={},pageSize", page, pageSize);
        Page<Category> pageInfo = new Page<>();
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id) {
        log.info("删除分类...id={}", id);
        categoryService.deleteCategory(id);
        return R.success();
    }

    @PutMapping
    public R update(@RequestBody Category category) {
        log.info("修改分类...category={}", category);
        categoryService.updateById(category);
        return R.success();
    }

    @GetMapping("/{id}")
    public R<Category> selectById(@PathVariable Long id) {
        log.info("回显数据...id={id}", id);
        Category category = categoryService.getById(id);
        if (category != null) {
            return R.success(category);
        }
        return R.error("没有查询到对应的分类信息");
    }

    @GetMapping("/list")
    public R<List<Category>> list( Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);

    }
}
